package controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

@SuppressWarnings("serial")
public class CheckValueServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		String name = (String) request.getParameter("domain");
		String value = "";
		
		if (name != null && !UrlHelper.checkDomain(name)) {
			check.put("name", "Please provice your domain.");
		} else if (name != null) {
			name = UrlHelper.getMainDomain(name);
		} 
		
		if (name != null && check.size() == 0) {
			try {
				String url = "http://www.mywebsiteworth.com/site/" + name;
				Document doc = Jsoup.connect(url).get();
				value = doc.select("#worth").html();
				value = value.replace("*", "");
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		request.setAttribute("value", value);
		try {
			request.getRequestDispatcher("/pages/check_value.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
